package devicedbgui;

import devicedbgui.data.Build;
import devicedbgui.data.BuildDAO;
import devicedbgui.data.Device;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/** Displays all builds associated with the current device */

public class BuildPanel extends javax.swing.JPanel {
    
    /** Reference to GUI class for accessing its variables */
    public GUI gui;
    Hashtable<Integer, Build> htBuild = new Hashtable<Integer, Build>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
 /** Constructor creates all components belonging to panel */   
    public BuildPanel() {
        initComponents();
        
    };
    /** Displays error messages */  
    public void showError(JFrame parent, String error)
    {
        JOptionPane.showMessageDialog(parent, error);
    }
    /** Displays builds associated with device */
    public void showBuilds(GUI gui, Device device)
    {
        this.gui = gui;
      
        BuildDAO dd = new BuildDAO(gui.connection);
        try {
            ArrayList<Build> testResults = dd.selectByDevice(device.record);
            DefaultTableModel model = (DefaultTableModel)tblBuild.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htBuild.clear();
            for (Build item : testResults){ 
                htBuild.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idBuild, sdf.format(item.start), sdf.format(item.end), item.Device_record});
            }
            
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
    }
    /** Displays all builds available in database  */
    public void showAllBuilds(GUI gui)
    {
        this.gui = gui;
     //   this.setTitle("All Builds");
        BuildDAO dd = new BuildDAO(gui.connection);
        try {
            ArrayList<Build> testResults = dd.selectAll();
            DefaultTableModel model = (DefaultTableModel)tblBuild.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htBuild.clear();
            for (Build item : testResults){ 
                htBuild.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idBuild, sdf.format(item.start), sdf.format(item.end), item.Device_record});
            }
             
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
    }
    /** Refreshes display of list of builds in database */
public void update()
    {
        BuildDAO dd = new BuildDAO(gui.connection);
        try {
            ArrayList<Build> records = dd.selectByDevice(gui.getDeviceRecord());
            DefaultTableModel model = (DefaultTableModel)tblBuild.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htBuild.clear();
            for (Build item : records){ 
                htBuild.put(new Integer(index++), item);
                model.addRow(new Object[]{item.idBuild, sdf.format(item.start), sdf.format(item.end), item.Device_record});
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblBuild = new javax.swing.JTable(){    public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !tblBuild.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (tblBuild.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }
    }
    ;
    btnViewRepairInfo = new javax.swing.JButton();
    btnViewExe = new javax.swing.JButton();
    btnAdd = new javax.swing.JButton();
    btnEdit = new javax.swing.JButton();
    btnDelete = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JSeparator();
    buildset = new javax.swing.JCheckBox();

    tblBuild.setAutoCreateRowSorter(true);
    tblBuild.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
        },
        new String [] {
            "Build ID", "Start", "End", "Device Record"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    tblBuild.setGridColor(new java.awt.Color(204, 204, 255));
    tblBuild.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane1.setViewportView(tblBuild);

    btnViewRepairInfo.setText("View Repair Info");
    btnViewRepairInfo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewRepairInfoActionPerformed(evt);
        }
    });

    btnViewExe.setText("View Exe");
    btnViewExe.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnViewExeActionPerformed(evt);
        }
    });

    btnAdd.setText("Add");
    btnAdd.setMnemonic(KeyEvent.VK_D);
    btnAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnAddActionPerformed(evt);
        }
    });

    btnEdit.setText("Edit");
    btnEdit.setMnemonic(KeyEvent.VK_I);
    btnEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnEditActionPerformed(evt);
        }
    });

    btnDelete.setText("Delete");
    btnDelete.setMnemonic(KeyEvent.VK_DELETE);
    btnDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnDeleteActionPerformed(evt);
        }
    });

    buildset.setText("Set As Build");
    buildset.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buildsetActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jSeparator1)
                    .addComponent(btnViewRepairInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnViewExe, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnAdd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnEdit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addComponent(buildset))
            .addGap(10, 10, 10))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnViewExe, btnViewRepairInfo});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(buildset)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnAdd)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnEdit)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnDelete)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 5, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnViewRepairInfo)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnViewExe)))
            .addContainerGap())
    );

    layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnViewExe, btnViewRepairInfo});

    }// </editor-fold>//GEN-END:initComponents
/** Shows all repair information pertaining to device */
private void btnViewRepairInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewRepairInfoActionPerformed
int selectedIndex = tblBuild.getSelectedRow();    
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    Build item = htBuild.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    gui.setBuildId(String.valueOf(item.idBuild));
    RepairInfoPanel r = new RepairInfoPanel();
    r.showRepairInfos(gui, item);
    
   
   gui.tab.add(r);
   gui.tab.setSelectedComponent(r); 
   gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("Repair Info") );
   
}//GEN-LAST:event_btnViewRepairInfoActionPerformed
/** Shows all executable files run in current build */
private void btnViewExeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewExeActionPerformed
int selectedIndex = tblBuild.getSelectedRow();    
    if (selectedIndex == -1){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    Build item = htBuild.get(new Integer(selectedIndex));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    gui.setBuildId(String.valueOf(item.idBuild));
    ExePanel e = new ExePanel();
    e.showExes(gui, item);
    
     
   gui.tab.add(e);
   gui.tab.setSelectedComponent(e); 
   gui.tab.setTabComponentAt( gui.tab.getSelectedIndex(), gui.TabSet("View Exe Files") );
   
}//GEN-LAST:event_btnViewExeActionPerformed
/** Add new build for current device */
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
//if (gui.connection == null)
        //return;
    EditBuildDlg dlg = new EditBuildDlg(gui, null, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        update();
    }
}//GEN-LAST:event_btnAddActionPerformed
/* Edit build information */
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
int[] selected = tblBuild.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    Build item = htBuild.get(new Integer(selected[0]));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    gui.setBuildId(String.valueOf(item.idBuild));
    EditBuildDlg dlg = new EditBuildDlg(gui, item, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        htBuild.remove(new Integer(selected[0]));        
        htBuild.put(new Integer(selected[0]), dlg.build);
        update();
        
    }
}//GEN-LAST:event_btnEditActionPerformed
/* Delete selected build */
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
int[] selected = tblBuild.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    // ask user if he surely wants to delete this record
    int option = JOptionPane.showConfirmDialog(gui.frame, "Are you sure to delete selected record(s)?", "Confirmation", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION)
    {        
        BuildDAO dd = new BuildDAO(gui.connection);
        try {
            for (int i = 0; i < selected.length; i++){
                Build item = htBuild.get(new Integer(selected[i]));   
                dd.delete(item.idBuild);
                htBuild.remove(new Integer(selected[i]));
            }           
            
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
        update();
    }
}//GEN-LAST:event_btnDeleteActionPerformed
/** Set selected build as the build associated with the current device */
private void buildsetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buildsetActionPerformed
    if(buildset.isSelected()){
    int[] selected = tblBuild.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }    
    Build item = htBuild.get(new Integer(selected[0]));
    gui.setBuildId(String.valueOf(item.idBuild));
    }
    else gui.setBuildId("(select an item)");
    
    ListSelectionModel rowSM = tblBuild.getSelectionModel();
        
        rowSM.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e)
        {
            if (e.getValueIsAdjusting())
            return;
            buildset.setSelected(false);
            gui.setBuildId("(select an item)");
        }});
}//GEN-LAST:event_buildsetActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnViewExe;
    private javax.swing.JButton btnViewRepairInfo;
    private javax.swing.JCheckBox buildset;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable tblBuild;
    // End of variables declaration//GEN-END:variables

}
